package code.wrtp.packets;

import code.exceptions.BadPduFormatException;
import code.wrtp.FrameControlType;

public class SetPredecessor implements Packet {

	protected byte FC; /* Frame control field */
	protected short SA; /* Source Address field */
	protected short RA; /* Ring Address */
	protected short DA; /* Destination Address */
	protected long nOn; /* Number of node */
	protected long genCnt; /* Generation counting */
	protected long seq; /* Sequence */

	public SetPredecessor(byte FC, short SA, short RA, short DA, long nOn, long genCnt,
			long seq) {

		this.FC = FC;
		this.SA = SA;
		this.RA = RA;
		this.DA = DA;
		this.nOn = nOn;
		this.genCnt = genCnt;
		this.seq = seq;
	}

	public byte getFC() {
		return FC;
	}

	public short getSA() {
		return SA;
	}

	public short getRA() {
		return RA;
	}

	public short getDA() {
		return DA;
	}

	public long getnOn() {
		return nOn;
	}

	public long getGenCnt() {
		return genCnt;
	}

	public long getSeq() {
		return seq;
	}

	@Override
	public byte[] toBytes() {
		return toString().getBytes();
	}

	@Override
	public String toString() {
		String token = FC + ";" + RA + ";" + DA + ";" + SA + ";" + nOn + ";"
				+ genCnt + ";" + seq;
		return token;
	}

	@Override
	public void ParseBytes(byte[] pduRaw) throws BadPduFormatException {
		
		String[] splittedPacket = new String(pduRaw).split(";",7);
		
		if (splittedPacket.length != 7) {
			throw new BadPduFormatException("Wrong packet format");
		}
		
		FC = Byte.parseByte(splittedPacket[0]);
		if ((FC != FrameControlType.SET_PREDECESSOR) && (FC != FrameControlType.VARAL_SET_PREDECESSOR))
			throw new BadPduFormatException("Wrong packet format");
		RA = Short.parseShort(splittedPacket[1]);
		DA = Short.parseShort(splittedPacket[2]);
		SA = Short.parseShort(splittedPacket[3]);
		nOn = Long.parseLong(splittedPacket[4]);
		genCnt = Long.parseLong(splittedPacket[5]);
		seq = Long.parseLong(splittedPacket[6]);
	}
}
